package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.InflowManagement;
import com.bf.electroplating.pojo.entity.SewageWarningConfig;
import com.bf.electroplating.pojo.vo.predischarge.*;
import com.bf.electroplating.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端预排口监测数据服务实现类
 */
@Slf4j
@Service
public class FrontPreDischargeServiceImpl implements IFrontPreDischargeService {

    @Autowired
    private ComCompanyService comCompanyService;

    @Autowired
    private IInflowManagementService inflowManagementService;

    @Autowired
    private ISewageWarningConfigService sewageWarningConfigService;

    @Override
    public PreDischargeMonitoringDataVO getPreDischargeMonitoringData() {
        PreDischargeMonitoringDataVO data = new PreDischargeMonitoringDataVO();
        
        // 获取所有企业
        List<ComCompany> companies = comCompanyService.list();
        List<EnterpriseInfoVO> enterprises = new ArrayList<>();
        
        for (ComCompany company : companies) {
            EnterpriseInfoVO enterpriseInfo = new EnterpriseInfoVO();
            enterpriseInfo.setCompanyId(company.getId());
            enterpriseInfo.setCompanyName(company.getCompanyName());
            enterpriseInfo.setStatus("正常");
            enterpriseInfo.setLastUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            
            // 获取该企业的废水类型
            List<WasteWaterTypeVO> wasteWaterTypes = getWasteWaterTypesByCompanyId(company.getId());
            enterpriseInfo.setWasteWaterTypes(wasteWaterTypes);
            
            enterprises.add(enterpriseInfo);
        }
        
        data.setEnterprises(enterprises);
        
        // 设置默认选中第一个企业
        if (!enterprises.isEmpty()) {
            data.setSelectedEnterprise(enterprises.get(0));
            data.setRunningData(getRunningDataByCompanyId(enterprises.get(0).getCompanyId()));
        }
        
        // 设置历史数据
        data.setHistoricalData(getHistoricalData());
        
        return data;
    }

    @Override
    public PreDischargeMonitoringDataVO getPreDischargeMonitoringDataByCompanyId(String companyId) {
        PreDischargeMonitoringDataVO data = new PreDischargeMonitoringDataVO();
        
        // 获取所有企业
        List<ComCompany> companies = comCompanyService.list();
        List<EnterpriseInfoVO> enterprises = new ArrayList<>();
        
        for (ComCompany company : companies) {
            EnterpriseInfoVO enterpriseInfo = new EnterpriseInfoVO();
            enterpriseInfo.setCompanyId(company.getId());
            enterpriseInfo.setCompanyName(company.getCompanyName());
            enterpriseInfo.setStatus("正常");
            enterpriseInfo.setLastUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            
            // 获取该企业的废水类型
            List<WasteWaterTypeVO> wasteWaterTypes = getWasteWaterTypesByCompanyId(company.getId());
            enterpriseInfo.setWasteWaterTypes(wasteWaterTypes);
            
            enterprises.add(enterpriseInfo);
        }
        
        data.setEnterprises(enterprises);
        
        // 设置指定企业为选中状态
        Optional<EnterpriseInfoVO> selectedEnterprise = enterprises.stream()
                .filter(e -> e.getCompanyId().equals(companyId))
                .findFirst();
        
        if (selectedEnterprise.isPresent()) {
            data.setSelectedEnterprise(selectedEnterprise.get());
            data.setRunningData(getRunningDataByCompanyId(companyId));
        }
        
        // 设置历史数据
        data.setHistoricalData(getHistoricalData());
        
        return data;
    }

    /**
     * 根据企业ID获取废水类型列表
     */
    private List<WasteWaterTypeVO> getWasteWaterTypesByCompanyId(String companyId) {
        List<WasteWaterTypeVO> wasteWaterTypes = new ArrayList<>();
        
        // 从污水预警配置表获取该企业配置的废水类型
        LambdaQueryWrapper<SewageWarningConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SewageWarningConfig::getCompanyId, companyId);
        List<SewageWarningConfig> configs = sewageWarningConfigService.list(wrapper);
        
        for (SewageWarningConfig config : configs) {
            WasteWaterTypeVO wasteWaterType = new WasteWaterTypeVO();
            wasteWaterType.setWasteWaterTypeId(config.getId());
            wasteWaterType.setWasteWaterTypeName(config.getWasteWaterType());
            wasteWaterType.setStatus("在线");
            wasteWaterType.setSelected(false);
            wasteWaterTypes.add(wasteWaterType);
        }
        
        return wasteWaterTypes;
    }

    /**
     * 根据企业ID获取运行数据
     */
    private List<MonitoringDataVO> getRunningDataByCompanyId(String companyId) {
        List<MonitoringDataVO> monitoringDataList = new ArrayList<>();
        
        // 获取该企业最新的监测数据
        LambdaQueryWrapper<InflowManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InflowManagement::getCompanyId, companyId);
        wrapper.orderByDesc(InflowManagement::getDetectionDate);
        wrapper.last("LIMIT 10"); // 获取最新的10条数据
        
        List<InflowManagement> inflowData = inflowManagementService.list(wrapper);
        
        // 按废水类型分组
        Map<String, List<InflowManagement>> groupedData = inflowData.stream()
                .collect(Collectors.groupingBy(InflowManagement::getWasteWaterType));
        
        for (Map.Entry<String, List<InflowManagement>> entry : groupedData.entrySet()) {
            String wasteWaterType = entry.getKey();
            List<InflowManagement> dataList = entry.getValue();
            
            if (!dataList.isEmpty()) {
                // 取最新的数据
                InflowManagement latestData = dataList.get(0);
                
                MonitoringDataVO monitoringData = new MonitoringDataVO();
                monitoringData.setWasteWaterType(wasteWaterType);
                monitoringData.setMonitoringFactors(getMonitoringFactors(latestData));
                monitoringData.setHexavalentChromium(latestData.getHexavalentChromiumValue());
                monitoringData.setTotalChromium(latestData.getTotalChromiumValue());
                monitoringData.setTotalNickel(latestData.getTotalNickelValue());
                monitoringData.setStatus("在线");
                
                monitoringDataList.add(monitoringData);
            }
        }
        
        return monitoringDataList;
    }

    /**
     * 获取监测因子字符串
     */
    private String getMonitoringFactors(InflowManagement data) {
        List<String> factors = new ArrayList<>();
        
        if ("1".equals(data.getMonitorHexavalentChromium())) {
            factors.add("六价铬");
        }
        if ("1".equals(data.getMonitorTotalChromium())) {
            factors.add("总铬");
        }
        if ("1".equals(data.getMonitorTotalNickel())) {
            factors.add("总镍");
        }
        
        return String.join(", ", factors);
    }

    /**
     * 获取历史数据
     */
    private HistoricalDataVO getHistoricalData() {
        HistoricalDataVO historicalData = new HistoricalDataVO();
        
        // 设置数据时间范围（最近7天）
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(6);
        historicalData.setDataTimeRange(startDate + " 至 " + endDate);
        
        // 创建数据系列
        List<DataSeriesVO> dataSeries = new ArrayList<>();
        String[] colors = {"#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E9", "#F8C471", "#82E0AA", "#F1948A", "#85C1E9", "#D7BDE2", "#A9DFBF", "#F9E79F", "#AED6F1"};
        
        // 获取所有企业的废水类型和监测因子组合
        List<ComCompany> companies = comCompanyService.list();
        int colorIndex = 0;
        
        for (ComCompany company : companies) {
            LambdaQueryWrapper<SewageWarningConfig> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SewageWarningConfig::getCompanyId, company.getId());
            List<SewageWarningConfig> configs = sewageWarningConfigService.list(wrapper);
            
            for (SewageWarningConfig config : configs) {
                // 为每个监测因子创建数据系列
                if ("1".equals(config.getMonitorHexavalentChromium())) {
                    DataSeriesVO series = new DataSeriesVO();
                    series.setSeriesName(config.getWasteWaterType() + "-六价铬");
                    series.setColor(colors[colorIndex % colors.length]);
                    series.setWasteWaterType(config.getWasteWaterType());
                    series.setMonitoringFactor("六价铬");
                    dataSeries.add(series);
                    colorIndex++;
                }
                
                if ("1".equals(config.getMonitorTotalChromium())) {
                    DataSeriesVO series = new DataSeriesVO();
                    series.setSeriesName(config.getWasteWaterType() + "-总铬");
                    series.setColor(colors[colorIndex % colors.length]);
                    series.setWasteWaterType(config.getWasteWaterType());
                    series.setMonitoringFactor("总铬");
                    dataSeries.add(series);
                    colorIndex++;
                }
                
                if ("1".equals(config.getMonitorTotalNickel())) {
                    DataSeriesVO series = new DataSeriesVO();
                    series.setSeriesName(config.getWasteWaterType() + "-总镍");
                    series.setColor(colors[colorIndex % colors.length]);
                    series.setWasteWaterType(config.getWasteWaterType());
                    series.setMonitoringFactor("总镍");
                    dataSeries.add(series);
                    colorIndex++;
                }
            }
        }
        
        historicalData.setDataSeries(dataSeries);
        
        // 生成模拟的图表数据点
        List<ChartDataPointVO> chartDataPoints = generateChartDataPoints(dataSeries, startDate, endDate);
        historicalData.setChartDataPoints(chartDataPoints);
        
        return historicalData;
    }

    /**
     * 生成图表数据点
     */
    private List<ChartDataPointVO> generateChartDataPoints(List<DataSeriesVO> dataSeries, LocalDate startDate, LocalDate endDate) {
        List<ChartDataPointVO> chartDataPoints = new ArrayList<>();
        Random random = new Random();
        
        // 为每个日期和每个数据系列生成数据点
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            for (DataSeriesVO series : dataSeries) {
                ChartDataPointVO dataPoint = new ChartDataPointVO();
                dataPoint.setTime(date.atStartOfDay().plusHours(12)); // 设置为中午12点
                dataPoint.setSeriesName(series.getSeriesName());
                
                // 根据监测因子生成不同的模拟数据
                BigDecimal value;
                switch (series.getMonitoringFactor()) {
                    case "六价铬":
                        value = BigDecimal.ZERO; // 六价铬通常为0
                        break;
                    case "总铬":
                        value = BigDecimal.valueOf(1 + random.nextDouble() * 8); // 1-9之间
                        break;
                    case "总镍":
                        value = BigDecimal.valueOf(1 + random.nextDouble() * 8); // 1-9之间
                        break;
                    default:
                        value = BigDecimal.valueOf(random.nextDouble() * 10);
                }
                
                dataPoint.setValue(value);
                chartDataPoints.add(dataPoint);
            }
        }
        
        return chartDataPoints;
    }
}
